package com.nbgroup.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nbgroup.context.BaseContext;
import com.nbgroup.mapper.ContractMapper;
import com.nbgroup.pojo.Contract;
import com.nbgroup.pojo.common.PageResult;
import com.nbgroup.pojo.dto.ContractDTO;
import com.nbgroup.service.ContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Override
    public PageResult queryCon(ContractDTO dto) {
        check(dto);
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        List<Contract> list=contractMapper.queryCon(dto);
        Page<Contract> p= (Page<Contract>) list;
        return new PageResult(200,"查询成功",p.getTotal(),p.getResult(),null);
    }

    private ContractDTO check(ContractDTO dto){
        if (dto.getPageNum() == null){
            dto.setPageNum(1);
        }
        if (dto.getPageSize() == null){
            dto.setPageSize(10);
        }
        return dto;
    }

    /**
     *添加合同
     */
    @Override
    public void add(Contract contract) {
        log.info("接收参数,{}",contract);
        contract.setCreateBy(String.valueOf(BaseContext.getCurrentId()));
        contract.setCreateTime(LocalDateTime.now());
        contract.setUpdateTime(LocalDateTime.now());
        contract.setId(generateRandomNumberString(17));
        contractMapper.insert(contract);
    }
    public  String generateRandomNumberString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
            if (i==0 && sb.toString().equals("0")){
                i--;
            }
        }
        return sb.toString();
    }


    /**
     * 合同详情
     */
    @Override
    public Contract getInfo(String id) {
        return contractMapper.getInfo(id);
    }

    /**
     * 修改合同
     */
    @Override
    public void update(Contract contract) {
        contract.setUpdateBy(BaseContext.getCurrentId().toString());
        contract.setUpdateTime(LocalDateTime.now());
        contractMapper.update(contract);
    }
}
